<template>
	<view class="selectcity">
		<view v-for="(item,index) in citys" :key="index" class="selectcity_main">
			<!-- 标题 -->
			<view class="title">{{ item.title  }}</view>
			<!-- 儿子们  -->
			<view v-for="child in item.children" :key="child.id" class="title_main">{{child.city_name}}</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				citys: [] //城市名数组
			};
		},

		onLoad() {
			uni.request({
				url: 'http://129.211.169.131:6368/citys',
				success: (res) => {
					console.log(res)
					// 1. 获取首字母 ['A','B','C'...'Z']
					let titleArr = res.data.map(obj => obj.city_pre.toUpperCase())
					titleArr = [...new Set(titleArr)]
					titleArr.sort() //a-b升序 b-a降序， sort默认ASCII码排序

					// 2. [{ title: 'A', children: []}]
					let newarr = titleArr.map((str) => {
						return {
							title: str,
							children: []
						}
					})

					// 3. 循环大数组，把每一个城市名push到newarr
					for (let obj of res.data) {
						// city_name: "上海"
						// city_pinyin: "Shanghai"
						// city_pre: "S"
						// city_short: "sh"
						// count: "316"
						// id: "1"
						let title = obj.city_pre.toUpperCase()
						for (let dataobj of newarr) {
							if (dataobj.title == title) {
								dataobj.children.push(obj)
							}
						}
					}

					this.citys = newarr
				}
			})
		}
	}
</script>

<style lang="scss">
	.selectcity{
		background-color: #f4f3f9;
	}
	.selectcity_main{
		margin-top: 10px;
	}
.title{
	height: 80rpx;
	display: flex;
	padding-left: 10px;
	align-items: center;
	background-color: #fff;
	margin-bottom: 5px;
}
.title_main{
	height: 80rpx;
	display: flex;
	padding-left: 10px;
	align-items: center;
	background-color: #fff;
	// margin-bottom: 5px;
	border-bottom: 1px solid #f4f3f9;
}
</style>
